<?php

namespace common\observer;

use common\model\EntityModel;
use common\model\UserModel;
use common\service\ChatService;
use support\SingletonTrait;
use teamones\dbeventObserver\interfaces\SplObserver;
use teamones\dbeventObserver\interfaces\SplSubject;

class TaskAssignInviteChatUser implements SplObserver
{
    use SingletonTrait;

    public $syncFields = [
        'executor',
        'assignee_producer',
        'assignee'
    ];

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        $changedFieldIntersect = array_intersect($this->syncFields, array_keys($updateData));
        if (empty($changedFieldIntersect)) {
            return;
        }
        $task = $subject->getSubjectData();
        $entity = model(EntityModel::class)->where(['id' => $task['entity_id']])->find();
        $chatService = new ChatService();
        try {
            $entityChat = $chatService->createEntityChat($entity);
            if (empty($entityChat)) {
                return;
            }
            $taskMember = [];
            if (!empty($updateData['executor']) && $updateData['executor'] > 0) {
                $taskMember[] = $updateData['executor'];
            }
            if (!empty($updateData['assignee_producer']) && $updateData['assignee_producer'] > 0) {
                $taskMember[] = $updateData['assignee_producer'];
            }
            if (!empty($updateData['assignee']) && $updateData['assignee'] > 0) {
                $taskMember[] = $updateData['assignee'];
            }
            if ($taskMember) {
                $user = model(UserModel::class)->field('id,union_id,name')->where(['id' => ['IN', $taskMember]])->select();
                if (empty($user)) {
                    return;
                }
                if (in_array('executor', $changedFieldIntersect)) {
                    // 调整执行人发送消息
                    $message['type'] = 'update_entity_task_executor_message';
                    $message = $chatService->getEntityTaskMessageTemplate($message, \request()->getUserId(), $entity, $task);
                    $chatService->pushEntityTaskMessage($message, $entityChat);
                }
                // 将新数据中的执行人邀请进群聊
                $requestData = [
                    'data' => [
                        'chat_global_id' => $entityChat['global_id'],
                        'user_id' => array_column($user, 'union_id'),
                    ],
                ];
                teamones_request('teamones-im', 'oauth/invite_chat_user', $requestData);
            }
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
